import time
from selenium.webdriver.common.by import By
from selenium import webdriver
from urllib import response
import requests
from urllib.parse import urljoin

BASE_URL = 'https://login2.scrape.center/'
LOGIN_URL = urljoin(BASE_URL, '/login')
INDEX_URL = urljoin(BASE_URL, '/page/1')
USERNAME = 'admin'
PASSWORD = 'admin'

# requests方法
response_login = requests.post(LOGIN_URL, data={
    'username': USERNAME,
    'password': PASSWORD
}, allow_redirects=False)  # 不允许重定向，否则拿不到返回数据

cookies = response_login.cookies

for i in range(3):
    response_index = requests.get(INDEX_URL, cookies=cookies)
    print(f'response_status:{response_index.status_code}')

# session方法
session = requests.session()
response_login = session.post(LOGIN_URL, data={
    'username': USERNAME,
    'password': PASSWORD})

for i in range(3):
    response_index = session.get(INDEX_URL)
    print(f'response_status:{response_index.status_code}')

# selenium方法

browser = webdriver.Chrome()
browser.get(LOGIN_URL)
browser.find_element(by=By.CSS_SELECTOR,
                     value='[name="username"]').send_keys(USERNAME)
browser.find_element(by=By.CSS_SELECTOR,
                     value='[name="password"]').send_keys(PASSWORD)
browser.find_element(by=By.CSS_SELECTOR, value='[type="submit"]').click()
time.sleep(10)

# TODO:拿到cookie
cookies = browser.get_cookies()
browser.close()

# TODO：加入cookie到session中
session = requests.session()
for cookie in cookies:
    session.cookies.set(
        cookie['name'], cookie['value']
    )

# TODO：重复请求首页3次
for i in range(3):
    response_index = session.get(INDEX_URL)
    print(f'response_status:{response_index.status_code}')
